package com.erbao.io.netty.refactor.rpc;

import com.erbao.io.netty.refactor.rpc.protocol.MyContent;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注册分发服务类
 */
public enum Dispatcher {
    dispatcher;

    public ConcurrentHashMap<String, Object> invokeMap = new ConcurrentHashMap<>();

    public void register(String key, Object value) {
        invokeMap.put(key, value);
    }

    public Object get (String key) {
        return invokeMap.get(key);
    }

    /**
     * 根据myContent中的信息，获取dispatcher中注册的类，反射执行结果返回
     */
    public Object getResult(MyContent requestContent) {
        Object object = Dispatcher.dispatcher.get(requestContent.getName());
        Object result;
        try {
            Method method = object.getClass().getMethod(requestContent.getMethodName(), requestContent.getParameterTypes());
            result = method.invoke(object, requestContent.getArgs());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}